/**************************************************************************************************
 * Name: AttachmentHandler
 * Object: Attachment
 * Purpose: 这个附件的parentid是不是合同.，如果是合同，判断合同的的生效状态,如果生效状态是已生效，抛一个错误提示说不能更新/删除附件
 * Requirement:
 * Author: yusm 
 * Create Date: 2017-5-17
 * Modify History: 
 
***************************************************************************************************/
public without sharing class AttachmentHandler implements Triggers.Handler{
    public void handle(){
    List<Attachment>  attachmentnew= new List<Attachment>();
        if (Trigger.isInsert||Trigger.isUpdate) {
            attachmentnew = (List<Attachment>)Trigger.new;
        }
        if (Trigger.isDelete) {
            attachmentnew = (List<Attachment>)Trigger.old;
            forbidDelete(attachmentnew);
        }
        //所有附件关联的合同的ID集合及附件集合
        Set<Id>  ContractIDs= new Set<Id>();
       
        
        List<Attachment> Attachmentlist = new List<Attachment>();
        for (Attachment att : attachmentnew) {
            if (att.parentid.getSobjectType()==Contract__c.SobjectType) {
                ContractIDs.add(att.parentid);
                Attachmentlist.add(att);
            }

        }
         //查询所有附件关联的合同信息,如果附件关联的合同的状态为已生效，则返回错误信息
        List<Contract__c>  ContractList= [select Id,Status__c from Contract__c where  id in :ContractIDs];
        for (Contract__c  con: ContractList) {
            for (Attachment att: Attachmentlist) {
                if (att.parentid==con.Id&&con.Status__c!=null&&con.Status__c=='已生效') {
                    att.adderror('已生效的合同不能添加和删除附件');
                }
            }
        }
        
    }

    //统计退货申请的附件数
    public static void countRetunOrderAtts (List<Attachment> atts ){

        Set<Id>  parents= new Set<Id>();
        Map<Id,Integer>  installWorkOrders = new Map<Id,Integer>();

        for (Attachment att : atts) {
            if(att.parentid.getSobjectType()==ReturnOrder__c.SobjectType ||  att.parentid.getSobjectType()==ScheduledCargo__c.SobjectType ||att.parentid.getSobjectType()== NoContractInstrumentApplication__c.SobjectType || att.parentid.getSobjectType()== OverdueExcess__c.SobjectType  ) parents.add(att.ParentId);
            if(att.parentid.getSobjectType() == WorkOrder__c.SobjectType && att.Name.contains('安装'))installWorkOrders.put(att.ParentId,1);
        }
        if(parents.size() == 0 &&installWorkOrders.keySet().size() == 0  )return;
        Map<Id,Integer> pMap = new Map<Id,Integer>();

        for (Attachment att : [select Id ,Name ,ParentId from Attachment where ParentId in:parents]) {
            Integer i = 1;
            if(att.ParentId.getSobjectType() == NoContractInstrumentApplication__c.SobjectType ){
                if(att.Name.contains('仪器签收单'))continue ;
            } 
            if(pMap.containsKey(att.ParentId)){
                
                i += pMap.get(att.ParentId);
            }


            pMap.put(att.ParentId ,i);

        }

        List<SObject> rList = new List<SObject>();

        for (Id rid: parents) {
            SObject r = rid.getSobjectType().newSobject();
            // ReturnOrder__c r = new ReturnOrder__c();
            // r.Id = rid;
            r.put('Id', rid);

            if(pMap.containsKey(rid)){
               // r.Count__c   = pMap.get(rid);
                r.put('Count__c', pMap.get(rid));
            }else{
                //r.Count__c = 0;
                r.put('Count__c',0);
            }
            rList.add(r);
        }
        if(rList.size() > 0)update rList;
        List<WorkOrder__c> installs = new List<WorkOrder__c>();
        for(Id woid : installWorkOrders.keyset()){
            installs.add(new WorkOrder__c(Id=woid,ReportNumber__c = installWorkOrders.get(woid)));
        }
        System.Debug(installs);

        if(installs.size()> 0 )update installs; 



    }
    public void forbidDelete(List<Attachment> attachmentnew){
    	
    	   User u = [select ProfileId from User where Id = :UserInfo.getUserId()];
    	  Profile r = [select name from Profile where Id =:u.ProfileId];
    	
    	 ///所有附件关联安装申请的ID 及附件的集合
        Set<Id> instanllIds = new Set<Id>();
        List<Attachment> installAtts =new List<Attachment>();
        
        //NC准入审批附件
        Set<Id> nccustomerId = new Set<Id>();
        List<Attachment> nccustomerAtts =new List<Attachment>();
        ///安装工单附件
        Set<Id> installWorkOrders = new Set<Id>();
        List<Attachment> installWorkOrdersAtts =new List<Attachment>();

        System.debug(attachmentnew);
          for (Attachment att : attachmentnew) {
           /// 安装申请
            if(att.parentid.getSobjectType()==InstallationApply__c.SobjectType){
            	instanllIds.add(att.parentid);
            	installAtts.add(att);
            }
              //准入审批
            if(att.parentid.getSobjectType() == NCCustomer__c.SobjectType){
            	nccustomerId.add(att.parentid);
            	nccustomerAtts.add(att);
            }
              ///安装工单
            if(att.parentid.getSobjectType() == WorkOrder__c.SobjectType){
            	installWorkOrders.add(att.parentid);
            	installWorkOrdersAtts.add(att);
            }
        }
        
     
    	///查询所有附件关联的安装申请的信息,如果安装申请的状态为已批准	不能删除
      for(InstallationApply__c ins :[select Id,Status__c from InstallationApply__c where id in: instanllIds])
      {
           for (Attachment att: installAtts) {
                if (att.parentid==ins.Id&&ins.Status__c!=null&&ins.Status__c=='已批准'&& r.Name != '系统管理员' && r.Name != 'System Administrator') {
                    att.adderror('不能删除附件!请联系管理员!');
                }
            }
      }
      ///查询所有附件关联的NC客户准入审批 如果状态为已审批
      for(NCCustomer__c cus :[select Id,ApprovalStatus__c from NCCustomer__c where Id in:nccustomerId]){
      		for (Attachment att: nccustomerAtts) {
                if (att.parentid==cus.Id&&cus.ApprovalStatus__c!=null&&cus.ApprovalStatus__c=='审批通过' && r.Name != '系统管理员' && r.Name != 'System Administrator') {
                    att.adderror('已经审批通过,不能删除附件!请联系管理员!');
                }
            }
      }
      ///安装工单附件
      for(WorkOrder__c wo :[select Id from WorkOrder__c where Id in: installWorkOrders and (RecordType.DeveloperName = 'InstallationOrder' or RecordType.DeveloperName= 'NonAgentInstallationOrder')]){
      		for(Attachment att : installWorkOrdersAtts){
            	if(att.parentid == wo.id && r.Name != '系统管理员' && r.Name != 'System Administrator'){
                	att.adderror('不能删除附件!请联系管理员!');
                }
            }
      }
      
        
    }
    
}